﻿(function ($) {
	$.bangoLinkTracking = function (el, options, i) {
		var base = this;
		base.$el = $(el);
		base.init = function () {
			var o = $.bangoLinkTracking.options = $.extend({}, $.bangoLinkTracking.defaultOptions, options),
				helpers = $.bangoLinkTracking.helperMethods,
				href = helpers.getHref(base.$el);
			if (!href) {
				return false;
			}
			if (!o.bangoNumber.length > 0) {
				return false;
			}
			var title = o.generateLinkTitle(base.$el), tid = o.generateTid(base.$el);  //this need to pass the element (not the title)
			var link = helpers.bangoUrl() + o.bangoNumber + helpers.createUrl(helpers.qs(title, href, o.bangoEventType, tid));
			if ($.bangoLinkTracking.parameterValidation.validate(o.parameters)) {
				link += helpers.createUrl(o.parameters);
			}
			if (o.testing) {
				o.testingFunction(link, o.testingResultElement, i);
			}
			else {
				helpers.bindImgEvent(base.$el, link);
			}
		};
		base.init();
	};
	$.bangoTrackSingleLink = function (options, href, title, tid) {
		var o = $.extend({}, $.bangoLinkTracking.defaultOptions, options),
			link = $.bangoLinkTracking.helperMethods.bangoUrl() + o.bangoNumber + $.bangoLinkTracking.helperMethods.createUrl($.bangoLinkTracking.helperMethods.qs(title, href, o.bangoEventType, tid));
		if ($.bangoLinkTracking.parameterValidation.validate(o.parameters)) {
			link += helpers.createUrl(o.parameters);
		}
		if (o.testing) {
			o.testingFunction(link, o.testingResultElement, 0);
		}
		else {
			var i = new Image();
			i.src = link;
		}
	};

	$.bangoLinkTracking.helperMethods = function () {
		var pub = {};
		var _undefined = 'undefined';
		var qualifyUrl = function (url) {
			var el = document.createElement("a");
			el.href = url;
			url = el.href;
			return url;
		};
		var createImg = function (link) {
			var i = new Image();
			i.src = link;
		};

		pub.bangoUrl = function () {
			return "http://bango.net/id/?register=n&bango=";
		};
		pub.bindImgEvent = function (el, link) {
			el.bind("click", function (e) {
				e.preventDefault();
				createImg(link, this.href);
				setTimeout(function (that) { return function () { window.location = that.href; }; } (this), 50);
			});
		};
		pub.getHref = function ($el) {
			var href = $el.attr("href");
			if (typeof href === _undefined || href === "" || href === "#") {
				return;
			}
			return encodeURI((href.indexOf("http") > -1 ? href : qualifyUrl(href)));
		};
		pub.qs = function (title, destUrl, eventType, tid) {
			return { "tid": tid, "desturl": destUrl, "b_t": eventType, "title": title };
		};
		pub.createUrl = function (queryString) {
			var returnString = "";
			for (var prop in queryString) {
				if (queryString.hasOwnProperty(prop)) {
					returnString += "&" + prop + "=" + queryString[prop];
				}
			}
			return returnString;
		};

		return pub;
	} ();
	$.bangoLinkTracking.parameterValidation = function () {
		var bgoparams = { bgo_campaign: { alias: "b_c", validation: { maxLen: 200} }, bgo_source: { alias: "b_s", validation: { maxLen: 200} }, bgo_medium: { alias: "b_m", validation: { maxLen: 200} }, bgo_content: { alias: "b_ct", validation: { maxLen: 200} }, bgo_term: { alias: "b_tr", validation: { maxLen: 200} }, bgo_owner: { alias: "b_o", validation: { maxLen: 200} }, bgo_region: { alias: "b_r", validation: { maxLen: 200} }, bgo_section: { alias: "b_ss", validation: { maxLen: 200} }, bgo_subsection: { alias: "b_sb", validation: { maxLen: 200} }, bgo_media: { alias: "b_md", validation: { maxLen: 200} }, bgo_author: { alias: "b_au", validation: { maxLen: 200} }, bgo_gender: { alias: "b_g", validation: { maxLen: 6, validArray: ["M", "MALE", "F", "FEMALE"]} }, bgo_age: { alias: "b_a", validation: { maxLen: 1, validArray: "A,B,C,D,E,F,G,H,I".split(",")} }, bgo_identity: { alias: "b_i", validation: { maxLen: 200} }, bgo_value: { alias: "b_v", validation: { maxLen: 200} }, bgo_valuecur: { alias: "b_vc", validation: { maxLen: 10} }, bgo_cost: { alias: "b_co", validation: { maxLen: 200} }, bgo_costcur: { alias: "b_cc", validation: { maxLen: 10} }, bgo_custom1: { alias: "b_1", validation: { maxLen: 200} }, bgo_custom2: { alias: "b_2", validation: { maxLen: 200} }, bgo_custom3: { alias: "b_3", validation: { maxLen: 200} }, bgo_custom4: { alias: "b_4", validation: { maxLen: 200} }, bgo_custom5: { alias: "b_5", validation: { maxLen: 200} }, bgo_custom6: { alias: "b_6", validation: { maxLen: 200} }, bgo_custom7: { alias: "b_7", validation: { maxLen: 200} }, bgo_custom8: { alias: "b_8", validation: { maxLen: 200} }, bgo_custom9: { alias: "b_9", validation: { maxLen: 200} }, bgo_custom10: { alias: "b_10", validation: { maxLen: 200}} }; ;
		var isParamNameValid = function (name) {
			return (bgoparams[name]);
		};
		var getParamFromAlais = function (alias) {
			for (var i in bgoparams) {
				if (bgoparams[i].alias === alias) return i;
			}
		};
		var checkValidation = function (para, value) {
			var rules = bgoparams[para].validation;
			for (var rule in rules) {
				if (rules.hasOwnProperty(rule)) {
					switch (rule) {
						case "maxLen":
							if (value.length > parseInt(rules[rule], 10)) return false;
							break;
						case "validArray":
							if (rules[rule].join(" ").indexOf(value.toUpperCase()) < 0) return false;
							break;
					}
				}
			}
			return true;
		};
		var isObjEmpty = function (obj) {
			for (var i in obj) {
				if (obj.hasOwnProperty(i)) return false;
			}
			return true;
		};
		return {
			validate: function (params) {
				var param, splitItemKey;
				if (isObjEmpty(params)) return false;
				for (var item in params) {
					if (item.indexOf("_") < 0) return false; // fail if no _
					splitItemKey = item.split("_");
					if (splitItemKey[0] !== "b" && splitItemKey[0] !== "bgo") return false; // fail if doesnt start with either b or bgo
					param = (splitItemKey[0] === "b" ? getParamFromAlais(item) : item);
					if (!isParamNameValid(param)) return false;
					if (!checkValidation(param, params[item])) return false; //fail if one of the params fail the validation checks
				}
				return true; //all succeeded! 
			}
		}
	} ();
	$.bangoLinkTracking.defaultOptions = {
		bangoNumber: "",
		bangoEventType: "click",
		generateLinkTitle: function (element) { return element.text(); },
		generateTid: function (element) { return element.text().replace(/[^a-zA-Z 0-9]+/g, ''); },
		parameters: {},
		testing: false,
		testingFunction: function () { return "No function defined"; },
		testingResultElement: null
	};
	$.bangoLinkTracking.options = {};


	$.fn.bangoLinkTracking = function (options) {
		return this.each(function (i) {
			(new $.bangoLinkTracking(this, options, i));
		});
	};
	$.fn.trackLink = function (options, href, title, tid) {
		return (new $.bangoTrackSingleLink(options, href, title, tid));
	};

})(jQuery);